package com.cci.kangdao.service.impl;

import com.cci.kangdao.dao.ServiceStationDao;
import com.cci.kangdao.dao.TypicalCaseDao;
import com.cci.kangdao.dao.model.DictionariesT;
import com.cci.kangdao.dao.model.EngineTypeT;
import com.cci.kangdao.dao.model.TypicalCaseT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.TypicalCaseService;
import com.cci.kangdao.utilTool.*;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 典型案例接口
 * 
 * @author fengshuai
 *
 */
@Service("typicalCaseService")
public class TypicalCaseServiceImpl implements TypicalCaseService {
	private Logger log = Logger.getLogger(this.getClass().getName());

	@Autowired
	private TypicalCaseDao typicalCaseDao;

	@Autowired
	private RedisClientUtils redisClientUtils;
	@Resource
	private PropertiesUtils propertiesUtils;
	@Resource
	private ServiceStationDao serviceStationDao;

	/**
	 * App用户获取典型案例接口
	 */
	@Override
	public ModelAndView getTypicalCase(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * "typicalCase": [{ "caseName": "ISG2.6无法启动", "showImg":
			 * "http://222x.png", "description": "ISG2.6无法启动", "cusComplaints":
			 * "无法启动、电控系统", "fileUrl": "http://222x.pdf", "isLogo":0 }]
			 * 
			 */
			/**
			 * 获取参数searchtxt 不为null
			 */
			if(map.get("searchTxt") == null){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			
			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);// 解密userid
			UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
			/**
			 * 典型案例查询
			 */
			if(map.get("searchTxt") != null && !map.get("searchTxt").toString().equals("")){
				map.put("searchTxt", "%"+map.get("searchTxt")+"%");
			}
			/**
			 * 1、康明斯、客户查询所有的课件 +级别 2、jv查询自己创建的课件 +级别 3、 dealer则查询企业授权服务站的课件 + 级别
			 * 4、普通用户没有权限
			 */
			List<EngineTypeT> engineTypeList = null;
			//授权机型的id
			String engineTypeID="";
			/*if(userT.getIsType() == 0){
				obj.put("status", 0);
				obj.put("msg", "");
				obj.put("typicalCase",  new JSONArray());
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}else if (userT.getIsType() == 1) {
				map.put("userType", 1);
				engineTypeList = serviceStationDao.findEngineTypeList(null);
			} else if (userT.getIsType() == 6) { // dealer用户组
				map.put("userType", 6);
				map.put("serviceStationID", "" + userT.getServiceStationID());
				engineTypeList = serviceStationDao.findEngineTypeListByStation(""+userT.getServiceStationID());
			} else {
				map.put("userType", userT.getIsType());
				map.put("companyID", "" + userT.getCompanyId());
				engineTypeList = serviceStationDao.findEngineTypeList(""+userT.getCompanyId());
			}*/
			
			/**
			 * 二期权限放开，任意渠道不再进行权限控制（所有用户都当作cci来看待）
			 */
			map.put("userType", 1);
			engineTypeList = serviceStationDao.findEngineTypeList(null);

//			String engineTypeID = "";
//			if (map.get("engineTypeID") != null) {
//				engineTypeID = "" + map.get("engineTypeID");
//			}
			if(engineTypeList != null){
				for (EngineTypeT engineTypeT : engineTypeList) {
					engineTypeID+=""+engineTypeT.getId()+",";
				}
				if(engineTypeID.endsWith(",")){
					engineTypeID=engineTypeID.substring(0,engineTypeID.length()-1);
				}
                map.put("engineTypeIDs", engineTypeID);
            }
            obj.put("status", 0);
            obj.put("msg", "");
            JSONObject content;
            JSONArray jsonArray = new JSONArray();
            PageHelper.startPage(page, pagesize);
            /**
             * 查询典型案例
             */
            List<String> engineTypeIDsList = StringToool.getStringList(MapUtils.getString(map, "engineTypeIDs"), ",");
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(engineTypeIDsList)) {
                map.put("engineTypeIDs", engineTypeIDsList);
            } else {
                map.remove("engineTypeIDs");
            }
            List<TypicalCaseT> typicalCaseList = typicalCaseDao.getTypicalCase(map);
            /**
             * 从redis中获取客户抱怨字典项
             */
            Map<String, DictionariesT> typicalCaseCusComplaintMap = getServiceStationImgRedis();
            if (typicalCaseList != null) {
                for (TypicalCaseT typicalCaseT : typicalCaseList) {
                    content = new JSONObject();
                    content.put("caseName", typicalCaseT.getCaseName());
                    content.put("showImg", typicalCaseT.getShowImg());
					content.put("description", typicalCaseT.getDescription());

					/**
					 * 查询字典项
					 */
					String cusComplaints = typicalCaseT.getCusComplaints();
					if (!cusComplaints.equals("")) {
						String[] split = cusComplaints.split(",");

						cusComplaints = "";
						for (int i = 0; i < split.length; i++) {
							if(typicalCaseCusComplaintMap.get(split[i]) != null){
								cusComplaints += typicalCaseCusComplaintMap.get(split[i]).getDvalue() + "、";
							}
						}
					} else {
						cusComplaints = "";
					}
					if (cusComplaints.endsWith("、")) {
						cusComplaints = cusComplaints.substring(0, cusComplaints.length() - 1);
					}
					content.put("cusComplaints", cusComplaints);

					content.put("fileUrl", typicalCaseT.getFileUrl());
					content.put("isLogo", typicalCaseT.getIsLogo());
					content.put("systime", PublicTool.dateTimeChangeChina(typicalCaseT.getSystime().toString().substring(0,19)));
					jsonArray.put(content);
				}
			}
			obj.put("typicalCase", jsonArray);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 从redis中去客户抱怨信息 如果redis中不存在就重新获取
	 * 
	 * @return
	 */
	private Map<String, DictionariesT> getServiceStationImgRedis() {

		Map<String, DictionariesT> typicalCaseCusComplaintMap = (Map<String, DictionariesT>) redisClientUtils
				.getObject("typicalCaseCusComplaintMap");
		if (typicalCaseCusComplaintMap == null) {
			/**
			 * 查询数据库得到客户抱怨信息
			 */
			List<DictionariesT> typicalCaseCusComplaints = typicalCaseDao.getTypicalCaseCusComplaints();
			if (typicalCaseCusComplaints != null && typicalCaseCusComplaints.size() > 0) {
				typicalCaseCusComplaintMap = new HashMap<String, DictionariesT>();
				for (DictionariesT bean : typicalCaseCusComplaints) {
					typicalCaseCusComplaintMap.put("" + bean.getDInt(), bean);
				}
				// 放入redis中
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				redisClientUtils.setObject("typicalCaseCusComplaintMap", typicalCaseCusComplaintMap, redisCacheTime);
			}
		}
		return typicalCaseCusComplaintMap;
	}
}
